package com.fourth_groups.shopping121store.ui.sight;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.fourth_groups.shopping121store.R;
import com.fourth_groups.shopping121store.bean.SightBean;
import com.fourth_groups.shopping121store.http.OkHttpClientUtils;
import com.fourth_groups.shopping121store.ui.sight.activity.WebActivity;
import com.fourth_groups.shopping121store.ui.sight.adapter.AutoRunThread;
import com.fourth_groups.shopping121store.ui.sight.adapter.AutoShowImgPagerAdapter;
import com.fourth_groups.shopping121store.ui.sight.adapter.SightLvAdapter;
import com.fourth_groups.shopping121store.utils.GsonImpl;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * ----------Dragon be here!----------/
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃  创建人 余兵兵
 * 　　┃　┳┛　┗┳　┃  时间:Administrator on 2016/10/10
 * 　　┃　　　　　　　┃  备注:发现
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃代码无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━by:coder-pig
 */
public class SightFragment extends Fragment {

    private String url="http://api.121dian.cn/v3/card?zone=find&offset=0&limit=10&access_token=bi2Qn6Oi8KJguHAebOaO";

    private ViewPager vpSight;
    private ListView lvSight;
    List<SightBean.DataBean.BlockBean> blocks;
    private SightLvAdapter sightLvAdapter;

    private AutoRunThread autoRunThread;
    private List<ImageView> images;



    //将解析好的json数据传到主线程
    Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                blocks= (List<SightBean.DataBean.BlockBean>) msg.obj;

                sightLvAdapter.setData(blocks);

                lvSight.setAdapter(sightLvAdapter);

                //设置sightVpAdapter的适配器
                AutoShowImgPagerAdapter sightVpAdapter=new AutoShowImgPagerAdapter(images,blocks);

                vpSight.setAdapter(sightVpAdapter);
                vpSight.setCurrentItem(1000);
            }
            if(msg.what==2){
                int position=msg.arg1;
                vpSight.setCurrentItem(position);
            }
        }
    };



    public SightFragment() {
        // Required empty public constructor
    }
    private static SightFragment sightFragment;
    public  static Fragment setFragment(){
        if (sightFragment==null)
            synchronized (SightFragment.class){
                if (sightFragment==null){
                    sightFragment=new SightFragment();
                }
            }
        return sightFragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_sight, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initView();//初始化控件


        loadData();//加载数据
        sightViewPagerOperation();//调用viewpager操作方法
        sightListOperation();//调用List操作方法

        refreshLayout();//下拉刷新

    }


    private void initView() {



        lvSight = (ListView) getActivity().findViewById(R.id.lv_sight);//实现详情滑动

        // ListView头部View
        View view = LayoutInflater.from(getContext()).inflate(R.layout.sight_vp_headlerview, null);
        // addHeaderView一定要在setAdapter前调用
        lvSight.addHeaderView(view);

        //实现图片轮播
        vpSight = (ViewPager) getActivity().findViewById(R.id.vp_sight);

        sightLvAdapter = new SightLvAdapter();



    }

    private void sightListOperation() { //ListView操作方法

        lvSight.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent=new Intent(getActivity(),WebActivity.class);
                intent.putExtra("urlImg",blocks.get(position).getItems().get(0).getUrl());
                startActivity(intent);
            }
        });

    }


    private void sightViewPagerOperation() {//进行viewpager操作


        images = new ArrayList<>();
        int[] imageId=new int[]{R.mipmap.sightone,R.mipmap.sighttwo,R.mipmap.sightthree};
        for (int i = 0; i <imageId.length ; i++) {
            ImageView image=new ImageView(getContext());
            image.setBackgroundResource(imageId[i]);
            images.add(image);
        }

        autoRunThread = new AutoRunThread(vpSight,mHandler, images);
        autoRunThread.startRun();
        autoRunThread.listener();


    }




    //    下载json和gson解析操作
    private void loadData(){
        //下载json
        OkHttpClientUtils.getDataAsync(getActivity(), url, new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
            }

            @Override
            public void onResponse(Response response) throws IOException {
                String json = response.body().string();

                //gson解析
                SightBean sightBean = GsonImpl.get().toObject(json, SightBean.class);
                List<SightBean.DataBean.BlockBean> block = sightBean.getData().getBlock();

                Message msg=Message.obtain();
                msg.what=1;
                msg.obj=block;
                mHandler.sendMessage(msg);

            }
        },new Object());

    }

    private void refreshLayout() {

        final SwipeRefreshLayout refreshLayout = (SwipeRefreshLayout) getActivity().findViewById(R.id.refresh_layout_sight);

        assert refreshLayout != null;
        //设置进度条的变化颜色
        refreshLayout.setColorSchemeResources(android.R.color.holo_orange_light);
        //设置进度圆圈的大小:默认值DEFAULT和大的值LARGE.
        refreshLayout.setSize(SwipeRefreshLayout.DEFAULT);

        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            //下拉刷新
            @Override
            public void onRefresh() {

                //延迟执行某任务
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //设置进度条的显示状态
                        refreshLayout.setRefreshing(false);
                    }
                }, 3000);
            }
        });
    }


    @Override
    public void onPause() {
        super.onPause();
        autoRunThread.stopRun();
    }

    @Override
    public void onResume() {
        super.onResume();
        autoRunThread.startRun();
    }


}
